package com.cqc.crm.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cqc.crm.domain.Customer;
import com.cqc.crm.domain.Dict;
import com.cqc.crm.service.CustomerService;
import com.cqc.crm.utils.PageBean;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.util.ValueStack;

public class CustomerAction extends BaseAction implements ModelDriven<Customer> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -9176812910048769004L;
	private Customer customer = new Customer();
	@Override
	public Customer getModel() {
		return customer;
	}

	private CustomerService customerService;
	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}


	/**
	 * 分页查找，调转到list.jsp
	 * @return
	 */
	public String findByPage() {
		DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
		
		//客户名
		String cust_name = customer.getCust_name();
		if(cust_name!=null && !cust_name.trim().isEmpty()) {
			criteria.add(Restrictions.like("cust_name", "%"+cust_name+"%"));
		}
		//客户级别
		Dict level = customer.getLevel();
		if(level!=null && !level.getDict_id().trim().isEmpty()) {
			criteria.add(Restrictions.eq("level.dict_id", level.getDict_id().trim()));
		}
		//客户来源
		Dict source = customer.getSource();
		if(source!=null && !source.getDict_id().trim().isEmpty()) {
			criteria.add(Restrictions.eq("source.dict_id", source.getDict_id().trim()));
		}
		
		PageBean<Customer> pageBean=customerService.findByPage(getPageCode(),getPageSize(),criteria);
		
		ValueStack vs = ActionContext.getContext().getValueStack();
		vs.push(pageBean);
		return "list";
	}

	
	private File upLoadFile;
	private String upLoadFileContentType;
	private String upLoadFileFileName;
	public void setUpLoadFile(File upLoadFile) {
		this.upLoadFile = upLoadFile;
	}
	public void setUpLoadFileContentType(String upLoadFileContentType) {
		this.upLoadFileContentType = upLoadFileContentType;
	}
	public void setUpLoadFileFileName(String upLoadFileFileName) {
		this.upLoadFileFileName = upLoadFileFileName;
	}


	/**
	 * 新增客户
	 * @return
	 */
	public String add() {
		String path=ServletActionContext.getRequest().getContextPath();
		
		int index = upLoadFileFileName.lastIndexOf(".");
		String lastName = upLoadFileFileName.substring(index);
		upLoadFileFileName=UUID.randomUUID().toString().replace("-", "")+lastName;
		
		
		File file = new File(path+"/"+upLoadFileFileName);
		try {
			FileUtils.copyFile(upLoadFile, file);
			customer.setFilepath(file.getAbsolutePath());
		} catch (IOException e) {
			e.printStackTrace();
		}
		customerService.add(customer);
		return "toList";
	}
	
	public String toUpdate() {
		//根据id获取customer对象
		customer =customerService.findCustomerById(customer.getCust_id());
		return "toUpdate";
	}
	
	public String update() throws IOException {
		//先根据Id查找到customer
		//再把jsp的值赋值到customer
		//判断是否有文件
		if(upLoadFileFileName!=null) {
			//表示上传了文件
			String oldPath = customer.getFilepath();
			//删除原有的filepath
			if(oldPath!=null && !oldPath.trim().isEmpty()) {
				File oldFile = new File(oldPath);
				oldFile.delete();
			}
			//保存新增文件
			int indexOf = upLoadFileFileName.indexOf(".");
			String lastName = upLoadFileFileName.substring(indexOf);
			upLoadFileFileName=UUID.randomUUID().toString().replace("-", "")+lastName;
			
			String path=ServletActionContext.getRequest().getContextPath()+"/";
			File file = new File(path+upLoadFileFileName);
			FileUtils.copyFile(upLoadFile, file);
			
			customer.setFilepath(path+upLoadFileFileName);
			
		}
		customerService.update(customer);
		return "toList";
	}
	
	/**
	 * 查找所有的客户
	 * @return
	 */
	public String findAll() {
		List<Customer> list=customerService.findAll();
		String json = JSON.toJSONString(list);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=utf8");
		response.setCharacterEncoding("utf-8");
		PrintWriter writer;
		try {
			writer = response.getWriter();
			writer.print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return NONE;
	}
}
